package com.sita.cfmoto.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.ActionMenuItem;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.login.LoginActivity;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.SessionUtils;


/**
 * Created by xiaodong on 16/3/4.
 */
public abstract class ActivityBase extends AppCompatActivity {

    private ActivityBase thisActivity;

    private CountDownTimer countDownTimer;

//    protected Foreground.Listener myListener = new Foreground.Listener() {
//        public void onBecameForeground() {
//            doInForeground();
//        }
//
//        public void onBecameBackground() {
//            String appStateStr = thisActivity.getIntent().getStringExtra(Constants.BUNDLE_APP_STATE);
//            if (!TextUtils.isEmpty(appStateStr)) {
//                AdvertiseManager.AppState appState = AdvertiseManager.AppState.valueOf(appStateStr);
//                AdvertiseManager.getInstance().setAppState(appState);
//                thisActivity.getIntent().removeExtra(Constants.BUNDLE_APP_STATE);
//            } else {
////                AdvertiseManager.getInstance().setAppState(AdvertiseManager.AppState.IN_BACKGROUND);
//            }
//            doInBackground();
//        }
//    };

//    private void doInBackground() {
//        // TODO: 2016/5/16
////        AdvertiseManager.getInstance().downloadAdvertise();
//    }

//    protected void doInForeground() {
//        // TODO: 2016/5/16
////        AdModel adModel = AdvertiseManager.getInstance().getAdModel();
////        if ((adModel == null) || adModel.playCount > 0) {
////            AdvertiseManager.getInstance().setAdShow(true);
////        }
////        VehicleUtils.refetchData();
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Foreground.get(this).addListener(myListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Foreground.get(this).removeListener(myListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!SessionUtils.isLoggedIn()) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            if (thisActivity != null && !thisActivity.isFinishing()) {
                thisActivity.finish();
            }
        } else {
            thisActivity = this;
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    private void showAdView() {
        LayoutInflater inflater = LayoutInflater.from(GlobalContext.getGlobalContext());

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        // 设置window type
        params.type = WindowManager.LayoutParams.TYPE_PHONE;
        params.format = PixelFormat.RGBA_8888;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        //加载需要的XML布局文件
        final RelativeLayout mInView = (RelativeLayout) inflater.inflate(R.layout.activity_adshow, null, false);

        final TextView timerView = (TextView) mInView.findViewById(R.id.timer);
        final ImageView bigpicView = (ImageView) mInView.findViewById(R.id.big_pic);


        final WindowManager wm = (WindowManager) GlobalContext.getGlobalContext()
                .getSystemService(Context.WINDOW_SERVICE);
        countDownTimer = new CountDownTimer(Constants.ADVERTISEMENT_SHOW_TIME,
                Constants.ADVERTISEMENT_INTERVAL) {
            @Override
            public void onTick(long l) {
                String time = String.valueOf((int) Math.round(l / 1000.0) - 1);
                timerView.setText(time);
            }

            @Override
            public void onFinish() {
                if (mInView.getParent() != null) {
                    wm.removeView(mInView);
                    countDownTimer = null;
                }
            }
        };
        countDownTimer.start();




    }

    protected void exitAppComplete() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            this.finishAffinity();
            System.exit(0);
        } else {
            this.finish();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    protected void initToolbar(@Nullable String title) {
        View toolbarView = findViewById(R.id.toolbar);
        if (toolbarView != null) {
            if (toolbarView instanceof RelativeLayout) {
                ImageView backView = (ImageView) toolbarView.findViewById(R.id.btn_back);
                if (backView != null) {
                    backView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onOptionsItemSelected(new ActionMenuItem(thisActivity, 0, android.R.id.home, 0, 0, ""));
                        }
                    });
                }
                if (title != null) {
                    TextView titleView = (TextView) toolbarView.findViewById(R.id.toolbar_title);
                    titleView.setText(title);
                }
            } else if (toolbarView instanceof Toolbar) {
                Toolbar toolbar = (Toolbar) toolbarView;
                setSupportActionBar(toolbar);
                ActionBar actionBar = getSupportActionBar();
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setDisplayShowTitleEnabled(false);
                toolbar.setNavigationIcon(R.mipmap.ic_back);

                if (title != null) {
                    TextView titleView = (TextView) toolbar.findViewById(R.id.toolbar_title);
                    titleView.setText(title);
                }
            }
        }
    }

    protected void initToolbar(@StringRes int titleResId) {
        View toolbarView = findViewById(R.id.toolbar);
        if (toolbarView != null) {
            if (toolbarView instanceof RelativeLayout) {
                ImageView backView = (ImageView) toolbarView.findViewById(R.id.btn_back);
                if (backView != null) {
                    backView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onOptionsItemSelected(new ActionMenuItem(thisActivity, 0, android.R.id.home, 0, 0, ""));
                        }
                    });
                }
                TextView titleView = (TextView) toolbarView.findViewById(R.id.toolbar_title);
                titleView.setText(getApplicationContext().getText(titleResId));
            } else if (toolbarView instanceof Toolbar) {
                Toolbar toolbar = (Toolbar) toolbarView;
                setSupportActionBar(toolbar);
                ActionBar actionBar = getSupportActionBar();
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setDisplayShowTitleEnabled(false);
                toolbar.setNavigationIcon(R.mipmap.ic_back);

                TextView titleView = (TextView) toolbar.findViewById(R.id.toolbar_title);
                titleView.setText(getApplicationContext().getText(titleResId));
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /*public void onEventMainThread(CallcarReceivedEvent event) {
        CallcarBean callcarBean = event.getCallcarBean();

        DriverNotificationDialog dialog = new DriverNotificationDialog(this, callcarBean);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }*/

    /*public void onEventMainThread(final HitchhikePayReceivedEvent event) {
        final String money = NumberUtils.formatCurrency(event.getMoney());
        UserNetworkHelper.getInstance().getUserInfo(event.getAccountid(), new GetAccountInfoListener() {
            @Override
            public void onSuccess(Account account) {
                String alertMsg = GlobalContext.getGlobalContext()
                        .getString(R.string.received_payment_from_customer, account.mNickName, money);
                ToastUtils.show(GlobalContext.getGlobalContext(), alertMsg);
                CcTicketEntity ticketEntity = PersistUtils.getTicket(Long.valueOf(event.getRentTripId()));
                if (ticketEntity != null){
                    ticketEntity.setMoney(event.getMoney().floatValue());
                    PersistUtils.saveTicket(ticketEntity);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
    }*/
}
